//
//  HEFindDoctorViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/16.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEFindDoctorViewController.h"
#import "HEFindServerMenuView.h"
#import "HEFindDoctorCell.h"
#import "HEDoctorInfoModel.h"
#import "HEDoctorMenuData.h"
#import "HEFindFiterModel.h"
#import "HEDoctorInfoDetailsViewController.h"

@interface HEFindDoctorViewController ()<UITableViewDelegate, UITableViewDataSource, HEFindServerMenuViewDelegate, QMUITextFieldDelegate>
 
@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, strong) NSString *departName;
@property (nonatomic, strong) NSString *hospitalName;
@property (nonatomic, strong) NSString *orderType;
@property (nonatomic, strong) NSString *orderField;
@property (nonatomic, strong) NSString *serverName;
@property (nonatomic, strong) NSString *minPrice;
@property (nonatomic, strong) NSString *maxPrice;
@property (nonatomic, strong) NSString *keyword;

@property (nonatomic, strong) QMUITextField *searchTF;
@property (nonatomic, strong) HEFindServerMenuView *menuView;
@property (nonatomic, strong) NSMutableArray <HEDoctorInfoModel *> * dataSourceArr;

@property (nonatomic, strong) HEDoctorMenuData *menuData;

@end

@implementation HEFindDoctorViewController

- (NSMutableArray<HEDoctorInfoModel *> *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"找医生";
    self.zx_navLineView.hidden = YES;
    
    _pageNum = 1;
    _pageSize = 10;
        
    [self initUI];
    [self.view addSubview:self.menuView];

    [self.view addSubview:self.tableView];
    [self setCustomTableView:self.tableView];
    [self showEmpty];
    
    [self loadChooseData];
    [self loadData];
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight + 50 + 50, KScreenWidth, KScreenHeight - ZXNavBarHeight -50 -50) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollsToTop = YES;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = KWhiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        __weak __typeof(&*self)weakSelf = self;
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.isFromHeadRefresh = YES;
            weakSelf.pageNum = 1;
            [weakSelf loadData];
        }];

        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            weakSelf.isFromHeadRefresh = NO;
            weakSelf.pageNum += 1;
            [weakSelf loadData];
        }];

        [_tableView registerClass:[HEFindDoctorCell class] forCellReuseIdentifier: @"HEFindDoctorCell"];
    }
    return _tableView;
}

- (void)initUI {
    // 搜索
    UIView *searchWarp = [UIView new];
    searchWarp.backgroundColor = KWhiteColor;
    [self.view addSubview:searchWarp];
    [searchWarp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).mas_offset(ZXNavBarHeight);
        make.left.right.equalTo(self.view);
        make.height.mas_offset(50);
    }];
    
    searchWarp.qmui_borderPosition = QMUIViewBorderPositionBottom;
    searchWarp.qmui_borderWidth = 1;
    searchWarp.qmui_borderColor = CSplitLineColor;
    
    // 输入框
    QMUITextField *searchTF = [QMUITextField new];
    _searchTF = searchTF;
    [searchWarp addSubview:searchTF];
    searchTF.backgroundColor = CViewBgColor;
    
    searchTF.placeholder = @"搜索医生";
    searchTF.placeholderColor = [UIColor colorWithHexString:@"#AAAAAA"];
    searchTF.delegate = self;
    searchTF.layer.cornerRadius = 20;

    UIView *leftWarp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 49, 18)];
    UIImageView *leftIcon = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"home_search")];
    leftIcon.frame = CGRectMake(20, 0, 18, 18);
    [leftWarp addSubview:leftIcon];
    searchTF.leftViewMode = UITextFieldViewModeAlways;
    searchTF.leftView = leftWarp;
 
    UIButton *searBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [searBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searBtn setTitleColor:CNavBgColor forState:UIControlStateNormal];
    searBtn.titleLabel.font = DYFont(17);
    [searchWarp addSubview:searBtn];
    [searBtn addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
    
    [searBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(searchWarp.mas_top);
        make.right.equalTo(searchWarp.mas_right).mas_offset(-15);
        make.height.mas_offset(40);
        make.width.mas_offset(60);
    }];
    
    [searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(searchWarp.mas_top);
        make.left.equalTo(searchWarp.mas_left).mas_offset(15);
        make.right.equalTo(searBtn.mas_left).mas_offset(-10);
        make.height.mas_offset(40);
    }];
}

- (void)searchClick {
    [_searchTF resignFirstResponder];
    [_tableView.mj_header beginRefreshing];
}

- (HEFindServerMenuView *)menuView
{
    if (!_menuView) {
        _menuView = [[HEFindServerMenuView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight + 50, KScreenWidth, 50) maxHeight:CGRectGetHeight(self.view.frame) - 50 - ZXNavBarHeight - 50];
        _menuView.delegate = self;
    }
    return _menuView;
}

#pragma mark -

- (void)loadChooseData {
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KdoctorChoose parameters:@{} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        self.menuData = [HEDoctorMenuData mj_objectWithKeyValues:response.data];
        [self dealFiterData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)dealFiterData {

    NSMutableArray *depts = @[].mutableCopy;
    NSMutableArray *ratios = @[].mutableCopy;
    NSMutableArray *brands = @[].mutableCopy;

    
    HEFindFiterModel *allItem = [HEFindFiterModel new];
    allItem.name = @"全部";
    allItem.value = @"";
    [depts addObject: allItem];
    
    NSMutableArray *hospArr = @[].mutableCopy;
    NSMutableArray *deptArr = @[].mutableCopy;

    // 筛选医院
    for (HEDoctorInfoModel *model in self.menuData.depts) {
        if (![hospArr containsObject:model.hospital_name]) {
            [hospArr addObject:model.hospital_name];
        }
    }
    
    // 筛选医院下的科室
    for (NSString *hospName in hospArr) {
        HEFindFiterModel *item = [HEFindFiterModel new];
        item.name = hospName;
        item.value = hospName;
        item.children = @[].mutableCopy;
        [depts addObject:item];
        
        if (![@"全部" isEqualToString:item.name]) {
            HEFindFiterModel *dept = [HEFindFiterModel new];
            dept.name = @"全部";
            [item.children addObject:dept];
        }
        
        for (HEDoctorInfoModel *model in self.menuData.depts) {
            if ([hospName isEqualToString:model.hospital_name]) {
                HEFindFiterModel *dept = [HEFindFiterModel new];
                dept.name = model.depart_name;
                dept.value = model.depart_name;
                [item.children addObject:dept];
            }
        }
    }
      
    
    NSArray *customRatios = @[@"综合", @"价格升序", @"价格降序", @"好评率", @"接诊率", @"服务量"];
    NSArray *customRatiosVal = @[@"", @"min_price,asc", @"min_price,desc", @"satisfaction,desc", @"approval,desc", @"server_total,desc"];

    for (int i = 0; i < customRatios.count; i++) {
        HEFindFiterModel *item = [HEFindFiterModel new];
        item.name = customRatios[i];
        if (i == 0) {
            item.value = @"";
            item.orderType = @"";
        }else {
            NSArray *arr = [customRatiosVal[i] componentsSeparatedByString: @","];
            item.value = arr[0];
            item.orderType = arr[1];
        }
        [ratios addObject:item];
    }
    
    for (HEDoctorInfoModel *model in self.menuData.services) {
        HEBrandModel *item = [HEBrandModel new];
        item.name = model.server_name;
        [brands addObject:item];
    }
    
    
//    HEBrandModel
//    self.menuView.deptList = depts;
    self.menuView.ratiosList = ratios;
    self.menuView.brandArr = brands;
 
}

- (void)loadData {
    
    HEPageRequest *params = [HEPageRequest new];
    params.pageNum = _pageNum;
    params.pageSize = _pageSize;
    [params addParmas: _serverName key:@"server_name"];
    [params addParmas: _orderType key:@"orderType"];
    [params addParmas: _maxPrice key:@"max_price"];
    [params addParmas: _minPrice key:@"min_price"];
    [params addParmas: _orderField key:@"orderField"];
//    [params addParmas: _departName key:@"depart_name"];
    [params addParmas: _selectOrgModel.hospital_name key:@"hospital_name"];
    [params addParmas: _keyword key:@"realname"];
    [params addParmas: [NSString stringWithFormat:@"%f", [UserManager sharedUserManager].currentCoordinate.longitude] key:@"longitude"];
    [params addParmas: [NSString stringWithFormat:@"%f", [UserManager sharedUserManager].currentCoordinate.latitude] key:@"latitude"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KdoctorList parameters:params success:^(id  _Nonnull responseObject) {

        if (self.isFromHeadRefresh) {
            [self.dataSourceArr removeAllObjects];
        }

        HEPageResponse *response = [HEPageResponse mj_objectWithKeyValues:responseObject];

        [self.dataSourceArr addObjectsFromArray:[HEDoctorInfoModel mj_objectArrayWithKeyValuesArray:response.data.list]];
        [self.tableView reloadData];

        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];

        if (self.dataSourceArr.count == 0) {
            [self showEmpty];
        }else {
            if (response.data.list.count < self.pageSize) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HEFindDoctorCell *cell = [_tableView dequeueReusableCellWithIdentifier:  @"HEFindDoctorCell"];
    cell.model = _dataSourceArr[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView fd_heightForCellWithIdentifier: @"HEFindDoctorCell" cacheByIndexPath:indexPath configuration:^(HEFindDoctorCell *cell) {
        cell.model = self.dataSourceArr[indexPath.row];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HEDoctorInfoModel *model = self.dataSourceArr[indexPath.row];
    HEDoctorInfoDetailsViewController *vc = [HEDoctorInfoDetailsViewController new];
    vc.userId = model.user_id;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - HEFindServerMenuViewDelegate
- (void)menuView:(HEFindServerMenuView *)view didSelectWithHospModel:(HEFindFiterModel *)hspModel deptModel:(HEFindFiterModel *)deptModel{
    _departName = deptModel.value;
    _hospitalName = hspModel.value;
    [self.tableView.mj_header beginRefreshing];
}

- (void)menuView:(HEFindServerMenuView *)view didSelectSortWithModel:(HEFindFiterModel *)model {
    _orderType = model.orderType;
    _orderField = model.value;
    [self.tableView.mj_header beginRefreshing];
}

- (void)menuView:(HEFindServerMenuView *)menuView didSelectConfirmWithBradIds:(NSString *)brandis minPrice:(NSString *)minPrice maxPrice:(NSString *)maxPrice {
    _serverName = brandis;
    _minPrice = minPrice;
    _maxPrice = maxPrice;
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - QMUITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    _keyword = text;
    
    self.isFromHeadRefresh = YES;
    self.pageNum = 1;
    [self loadData];
    return YES;
}

@end
